<template>
	<view class="popup">
		<view class="popup-title">
			<view class="inner">上传文件</view>
		</view>

		<u-upload
			upload-text="选择文件"
			:action="uploadUrl"
			:file-list="data.list"
			:auto-upload="true"
			:header="header"
			:form-data="formData"
			@on-remove="fileRemove"
			@on-uploaded="fileUploaded"
			@on-choose-complet="fileChoose"
			@on-choose-fail="fileChoose"
		></u-upload>
		<view class="btn">
			<view class="inner">
				<u-button type="primary" :disabled="disabled" @click="confirm">确定</u-button>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	name: 'uploadFile',
	props: {
		data: {
			type: Object,
			default() {
				return {};
			},
		},
	},
	watch: {
		data: {
			handler(val) {
				this.setFiles(val.list);
			},
			deep: true,
			immediate: true,
		},
	},
	data() {
		return {
			disabled: false,
			envName: 'development',
			uploadUrl: '',
			header: {},
			formData: {},
			// 已将上传的文件
			files: [],
		};
	},
	mounted() {
		this.initUploadData();
		this.envName = process.env.NODE_ENV;
	},
	methods: {
		// 初始化上传所需数据
		initUploadData() {
			this.uploadUrl = this.$enum.upload.url;
			let token = uni.getStorageSync('Admin-Token');
			this.header = {
				'Admin-Token': token,
			};

			// 上传的所有文件都用一个id
			this.formData = {
				batchId: this.data.batchId,
			};

			console.log(this.data.batchId);
		},
		// 文件选择后
		fileChoose() {
			this.disabled = true;
		},
		// 所选文件都上传完成
		fileUploaded(lists, name) {
			this.setFiles(lists);
			this.disabled = false;
		},
		// 删除文件
		fileRemove(index, lists, name) {
			this.setFiles(lists);
		},
		// 设置上传图片的缓存
		setFiles(lists) {
			this.files = [];
			let baseUrl = this.$env[this.envName].BASE_URL;
			lists.forEach((v) => {
				let url = v.response ? v.response.url : v.url;
				this.files.push({
					url: url.indexOf(baseUrl) >= 0 ? url : baseUrl + url,
				});
			});
		},
		confirm() {
			this.$emit('selected', 'file', this.files);
		},
	},
};
</script>

<style lang="scss" scoped>
.u-upload {
	margin: 15px;
}
.btn {
	height: 60px;
	.inner {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 20;
		background: #fff;
		padding: 10px 15px;
	}
}
</style>